"use client"

import {useState} from "react"
import {ChevronDown, ChevronRight, File, Folder} from "lucide-react"
import {cn} from "@/lib/utils"

export interface FileTreeItem {
    name: string
    path: string
    type: "file" | "directory"
    children?: FileTreeItem[]
}

interface FileTreeProps {
    items: FileTreeItem[]
    onSelect?: (item: FileTreeItem) => void
    selectedPath?: string
}

export function FileTree({items, onSelect, selectedPath}: FileTreeProps) {
    return (
        <div className="p-2">
            {items.map((item) => (
                <FileTreeNode key={`${item.path}-${item.name}`} item={item} onSelect={onSelect}
                              selectedPath={selectedPath} level={0}/>
            ))}
        </div>
    )
}

interface FileTreeNodeProps {
    item: FileTreeItem
    onSelect?: (item: FileTreeItem) => void
    selectedPath?: string
    level: number
}

function FileTreeNode({item, onSelect, selectedPath, level}: FileTreeNodeProps) {
    const [expanded, setExpanded] = useState(level < 1)
    const isDirectory = item.type === "directory"
    const isSelected = selectedPath === item.path

    const handleClick = () => {
        if (isDirectory) {
            setExpanded(!expanded)
        } else if (onSelect) {
            onSelect(item)
        }
    }

    return (
        <div>
            <div
                className={cn(
                    "flex items-center py-1 px-2 rounded-md cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800",
                    isSelected && "bg-primary/10 text-primary",
                )}
                style={{paddingLeft: `${level * 12 + 4}px`}}
                onClick={handleClick}
            >
                {isDirectory ? (
                    <span className="mr-1">
            {expanded ? <ChevronDown className="h-4 w-4"/> : <ChevronRight className="h-4 w-4"/>}
          </span>
                ) : (
                    <File className="h-4 w-4 mr-1"/>
                )}
                {isDirectory ? <Folder className="h-4 w-4 mr-2"/> : null}
                <span className="text-sm">{item.name}</span>
            </div>
            {isDirectory && expanded && item.children && (
                <div>
                    {item.children.map((child) => (
                        <FileTreeNode
                            key={`${child.path}-${child.name}`}
                            item={child}
                            onSelect={onSelect}
                            selectedPath={selectedPath}
                            level={level + 1}
                        />
                    ))}
                </div>
            )}
        </div>
    )
}
